import os

__tags__ = "file, list, directory"

class FindFiles(ni.Node):
    ''' Find files given a root path '''
    
    root = ni.Path(default="", doc="The root path from where to look for files")
    recursive = ni.Bool(default=False, doc="Wether to look in all sub-folders")
    extentions = ni.List(itemtype=ni.String(), doc="What kind of extentions the files must have")
    files = ni.List(itemtype=ni.File(), depends=(root, recursive, extentions,), doc="The files found")
    
    def recursive_iter(self, root):
        for root, dirs, files in os.walk(root):
            for file in files:
                yield root + os.sep + file
                
    def non_resursive_iter(self, root):
        for file in os.listdir(root):
            filepath = root + os.sep + file
            if not os.path.isfile(filepath):
                continue
            yield filepath
    
    def compute_files(self):
        if not self.root:
            return []
        files = []
        if not os.path.isdir(self.root):
            return []
        
        filepath_iter = self.recursive_iter if self.recursive else self.non_resursive_iter
        
        for filepath in filepath_iter(self.root):
            name, ext = os.path.splitext(filepath)
            if self.extentions and not ext[1:] in self.extentions:
                continue
            files.append(filepath)
        return files